clc,clear;
close all
rng(222);%固定随机数种子
%数据
X=[randn(1,100);randn(1,100)]';
%聚类种类 
K = 4; 
%迭代次数
iters = 100; 
centroids = icentroids(X, K);
s=zeros(K,size(X,2));
% 迭代更新簇分配和簇质心 
for i = 1:iters 
    % 簇分配 
    labels = aslabels(X, centroids); 
    % 更新簇质心 
    centroids = upcentroids(X, labels, K); 
    if s==centroids
        break;
    else
       s=centroids;
    end
end 
%散点图(分类)
x1=find(labels==1);
x2=find(labels==2);
x3=find(labels==3);
x4=find(labels==4);
figure
scatter(X(x1,1),X(x1,2),"blue")
hold on
scatter(X(x2,1),X(x2,2),'red')
scatter(X(x3,1),X(x3,2),'green')
scatter(X(x4,1),X(x4,2),'yellow')
scatter(centroids(:,1),centroids(:,2),'black')

% 簇分配函数 
function labels = aslabels(X, centroids) 
    [~, labels] = min(pdist2(X, centroids, 'squaredeuclidean'), [], 2); 
end 
 
% 初始化簇质心函数 
function centroids = icentroids(X, K) 
    % 随机选择一个数据点作为第一个质心 
    centroids = X(randperm(size(X, 1), 1), :); 
    % 选择剩余的质心 
    for i = 2:K 
        D = pdist2(X, centroids, 'squaredeuclidean'); 
        D = min(D, [], 2); 
        D = D / sum(D); 
        centroids(i, :) = X(find(rand < cumsum(D), 1), :); 
    end 
end 
 
% 更新簇质心函数 
function centroids = upcentroids(X, labels, K) 
    centroids = zeros(K, size(X, 2)); 
    for i = 1:K 
        centroids(i, :) = mean(X(labels == i, :), 1); 
    end 
end